<?php 
class News_feed_Widget_recent_news extends WP_Widget{
	function __construct(){
		$widget_ops = array('classname'=>'widget_recent_news', 'description'=>__('Output newest news.', 'News-feed'));
		parent::__construct('recent_news', __('recent news', 'News-feed'), $widget_ops);
		
		add_action('save_post', array(&$this, 'flush_recent_news'));
		add_action('delete_post', array(&$this, 'flush_recent_news'));
	}
	
	function flush_recent_news(){
		wp_cache_delete('widget_recent_news', 'widget');
	}
	
	function get_menu_nav( $args = array() ){
		static $menu_id_slugs = array();
		
		$defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '',
				'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
				'depth' => 0, 'walker' => '', 'theme_location' => '' );
		
		$args = wp_parse_args( $args, $defaults );
		$args = apply_filters( 'wp_nav_menu_args', $args );
		$args = (object) $args;
		
		// Get the nav menu based on the requested menu
		$menu = wp_get_nav_menu_object( $args->menu );
		
		// Get the nav menu based on the theme_location
		if ( ! $menu && $args->theme_location && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args->theme_location ] ) )
			$menu = wp_get_nav_menu_object( $locations[ $args->theme_location ] );
		
		// get the first menu that has items if we still can't find a menu
		if ( ! $menu && !$args->theme_location ) {
			$menus = wp_get_nav_menus();
			foreach ( $menus as $menu_maybe ) {
				if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {
					$menu = $menu_maybe;
					break;
				}
			}
		}
		
		// If the menu exists, get its items.
		if ( $menu && ! is_wp_error($menu) && !isset($menu_items) )
			$menu_items = wp_get_nav_menu_items( $menu->term_id );
		
		// If no menu was found or if the menu has no items and no location was requested, call the fallback_cb if it exists
		if ( ( !$menu || is_wp_error($menu) || ( isset($menu_items) && empty($menu_items) && !$args->theme_location ) )
				&& $args->fallback_cb && is_callable( $args->fallback_cb ) )
			return call_user_func( $args->fallback_cb, (array) $args );
		
		// If no fallback function was specified and the menu doesn't exists, bail.
		if ( !$menu || is_wp_error($menu) )
			return false;
		
		$nav_menu = $items = '';
		
		$show_container = false;
		if ( $args->container ) {
			$allowed_tags = apply_filters( 'wp_nav_menu_container_allowedtags', array( 'div', 'nav' ) );
			if ( in_array( $args->container, $allowed_tags ) ) {
				$show_container = true;
				$class = $args->container_class ? ' class="' . esc_attr( $args->container_class ) . '"' : ' class="menu-'. $menu->slug .'-container"';
				$id = $args->container_id ? ' id="' . esc_attr( $args->container_id ) . '"' : '';
				$nav_menu .= '<'. $args->container . $id . $class . '>';
			}
		}
		
		// Set up the $menu_item variables
		_wp_menu_item_classes_by_context( $menu_items );
		
		$sorted_menu_items = array();
		foreach ( (array) $menu_items as $key => $menu_item )
			$sorted_menu_items[$menu_item->menu_order] = $menu_item;
		
		unset($menu_items);
		
		$sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args );
		
		return $sorted_menu_items;
	}
	
	function widget( $args, $instance ) {
		$caches = wp_cache_get('widget_recent_news', 'widget');
		
		if (!is_array($caches))
			$cache = array();
		
		if ( ! isset( $args['widget_id'] ) )
			$args['widget_id'] = $this->id;
		
		if ( isset( $cache[ $args['widget_id'] ] ) ) {
			echo $cache[ $args['widget_id'] ];
			return;
		}
		
		$menus = $this->get_menu_nav( array( 'theme_location' => 'primary' ) );
		if ( !is_array($menus)){
			return;
		}
		
		foreach($menus as $key => $item){
			if ( $item->current){
				break;
			}
		}
		$key += absint($instance['category']);
		
		$key = $key % count($menus);
		if ($key == 0){
			$key = count($menus);
		}
		
		$request_type = '';
		switch($menus[$key]->object){
			case 'category':
				$request_type = 'cat';
				break;
			default:
				break;
		}
		
		ob_start();
		extract($args);
		$title = apply_filters('widget_title', empty($instance['title']) ? __('recent news', 'News-feed') : $instance['title'], $instance, $this->id_base);
		if (empty($instance['number']) || $number = absint($instance['number']))
			$number = 5;
		
		$title .= $menus[$key]->title;
		
		$r = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true , 'suppress_filters' => true, $request_type => $menus[$key]->object_id) ) );
		if ($r->have_posts()) :
		?>
		<?php echo $before_widget; ?>
		<?php if ( $title )
				echo $before_title . $title ; ?>
		<a class="more" href="<?php echo $menus[$key]->url;?>"><?php _e('more...', 'News-feed')?></a>
		<?php echo $after_title;?>
		<?php  while ($r->have_posts()) : $r->the_post(); ?>		
				<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
					<div class="pull-left img-box">
					<a target="_blank" href="<?php the_permalink(); ?>">
						<img src="<?php echo News_feed_post_image_source(get_the_ID(), false);?>" /> 
					</a>
					</div>
					<div class="widget-content">
					<h4 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h4>
					<span class="widget-post-autor"><a target="_blank" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) );?>"><?php echo get_the_author();?></a></span>
					<p><time><?php echo esc_html( get_the_date() );?></time></p>
					</div>
				</article>								
				<?php endwhile; ?>
			<?php echo $after_widget; ?>
			<?php
			// Reset the global $the_post as this query will have stomped on it
			wp_reset_postdata();			
		endif;
						
		$cache[$args['widget_id']] = ob_get_flush();
		wp_cache_set('widget_recent_news', $cache, 'widget');
	}
	
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['number'] = (int) $new_instance['number'];
		$instance['category'] = (int) $new_instance['category'];
		$this->flush_recent_news();
	
		$alloptions = wp_cache_get( 'alloptions', 'options' );
		if ( isset($alloptions['widget_recent_news']) )
			delete_option('widget_recent_news');
	
		return $instance;
	}
	
	function form( $instance ) {
		$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
		$number = isset($instance['number']) ? absint($instance['number']) : 5;
		$category = isset($instance['category']) ? absint($instance['category']) : 0;
		?>
			<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
			<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
	
			<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to show:'); ?></label>
			<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
			
			<p><label for="<?php echo $this->get_field_id('category'); ?>"><?php _e('Category to show:', 'News-feed'); ?></label>
			<input id="<?php echo $this->get_field_id('category'); ?>" name="<?php echo $this->get_field_name('category'); ?>" type="text" value="<?php echo $category; ?>" size="3" /></p>
	<?php
		}
};

?>